import { h, render } from 'vue'
import EmailCode from '@/components/forms/EmailCode.vue'

// 定义函数返回类型
interface CaptchaResult {
  success: boolean
  code?: string
}

/**
 * 显示验证码弹窗并返回验证结果
 * @returns Promise<CaptchaResult> 验证结果
 */
export function showCaptcha(): Promise<CaptchaResult> {
  return new Promise((resolve) => {
    // 创建一个容器元素
    const container = document.createElement('div')
    document.body.appendChild(container)
    
    // 关闭并清理组件
    const close = () => {
      setTimeout(() => {
        render(null, container)
        document.body.removeChild(container)
      }, 300)
    }
    
    // 创建组件实例
    const vnode = h(EmailCode, {
      onConfirm: (code: string) => {
        close()
        
        resolve({ success: true, code })
      },
      onCancel: () => {
        close()
        resolve({ success: false })
      }
    })
    
    // 渲染组件
    render(vnode, container)
    
    // 通过 ref 调用子组件的 show 方法
    setTimeout(() => {
      if (vnode.component && vnode.component.exposed) {
        vnode.component.exposed.show()
      }
    }, 0)
  })
}